<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-tabs
          v-model="activeName"
          @tab-click="handleClick"
          class="hatswitch"
        >
          <el-tab-pane label="价格配置" class="hatswitch1" name="first">
            <el-col :span="24" class="exhibition">
              <div class="tabers">
                <el-table :data="listData" style="width: 100%">
                  <el-table-column label="业务名称">
                    <template slot-scope="scope">
                      {{ scope.row.merchandise__name }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="price" label="参考价格">
                    <template slot-scope="scope">
                      <!-- {{ scope.row.price+scope.row.unit }} -->
                      {{ scope.row.price }}
                    </template>
                  </el-table-column>
                </el-table>
                <el-table :data="dataList" style="width: 100%">
                  <!-- 修改价格 -->
                  <el-table-column label="修改价格">
                    <template slot-scope="scope">
                      <el-col :span="6">
                        <el-input
                          v-model="scope.row.price"
                          oninput="value=value.replace(/^\.+|[^\d.]/g,'')"
                          class="actualPriceBt"
                          maxlength="5"
                          @keyup.enter.native="confirm"
                        ></el-input>
                      </el-col>
                    </template>
                  </el-table-column>
                  <!-- 实际价格 -->
                </el-table>
              </div>
            </el-col>
            <el-button
              type="primary"
              class="confirm quedinganniu"
              @click="confirm"
              >确定</el-button
            >
          </el-tab-pane>
          <el-tab-pane label="公告配置" name="second" class="second">
            <el-form
              :model="announcement"
              label-width="80px"
              class="announcement"
            >
              <el-form-item label="公告标题">
                <el-input
                  v-model="announcement.title"
                  placeholder="请输入公告标题"
                ></el-input>
              </el-form-item>
              <el-form-item
                :label="mobile > 768 ? '公告内容' : null"
                :style="mobile > 768 ? '' : 'margin-left: -80px;'"
              >
                <!-- <el-input
                  type="textarea"
                  :autosize="{ minRows: 8 }"
                  placeholder="请输入内容"
                  v-model="announcement.content"
                ></el-input> -->
                <Editor
                  @editorVal="editorVal"
                  :contentstr="announcement.content"
                ></Editor>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  @click="saveAnnouncement"
                  class="saveAnnouncement"
                  :style="
                    mobile > 768 ? '' : 'margin-top:230px;margin-left: 30px;'
                  "
                  >保存</el-button
                >
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="客服配置" name="third" class="third">
            <el-form class="uploadform">
              <el-form-item label="客服配置">
                <el-upload
                  action="http://82.156.188.202:80/uploadPic"
                  list-type="picture-card"
                  :file-list="servicearr"
                  :on-success="servicePreview"
                  :on-remove="imgRemove"
                  :limit="3"
                  :on-exceed="exceed"
                  accept=".jpg,.jpeg,.png,.gif,.bmp,.pdf,.JPG,.JPEG,.PBG,.GIF,.BMP,.PDF"
                  :before-upload="beforeAvatarUpload"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
              </el-form-item>
              <el-form-item label="商务配置">
                <el-upload
                  action="http://82.156.188.202:80/uploadPic"
                  list-type="picture-card"
                  :file-list="businessarr"
                  :on-success="businessPreview"
                  :on-remove="imgRemove"
                  :limit="1"
                  :on-exceed="exceed"
                  accept=".jpg,.jpeg,.png,.gif,.bmp,.pdf,.JPG,.JPEG,.PBG,.GIF,.BMP,.PDF"
                  :before-upload="beforeAvatarUpload"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { _debounce1 } from "../../public/App";
import Editor from '@/components/Editor'
export default {
  props: {},
  data() {
    return {
      base: 'http://82.156.188.202:80/',
      photoecho: [],
      ceshi: [],
      price_list: [],
      listData: [],
      dataList: [],
      mobile: document.body.clientWidth,
      activeName: "first",
      actualPrice: [],
      initialPrice: [],
      announcement: {
        title: "",
        content: "",
      },
      servicearr: [],
      businessarr: [],
      showarr: []
    };
  },
  computed: {},
  created() {
    this.priceLst();
    // this.serviceImg()
  },
  mounted() { },
  watch: {},
  methods: {
    editorVal(editorVal) {
      this.announcement.content = editorVal;
    },
    exceed(files, fileList) {
      console.log('exceed');
      this.$message({
        showClose: true,
        message: "达到上限了哦~",
        type: "warning",
        duration: 1800,
      });
    },
    //获取图片回显
    async serviceImg() {
      // 客服配置
      let businessarr = this.businessarr
      //商务配置
      let servicearr = this.servicearr
      const [err, res] = await this.$http.request({
        url: "/selfPic",
        method: "GET",
      });
      if (err) return;
      this.businessarr = res.data.data.pic_list.filter((item) => {
        return item.img_type === 2
      }).map(res=>{
        res.url = 'http://82.156.188.202:80/'+res.img_url
        return res
      });
      this.servicearr = res.data.data.pic_list.filter((item) => {
        return item.img_type === 1
      }).map(res=>{
        res.url = 'http://82.156.188.202:80/'+res.img_url
        return res
      });
      console.log(this.businessarr)
    },
    //提示大小不能超过2mb
    beforeAvatarUpload(file) {
      console.log('beforeAvatarUpload')
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message({
          showClose: true,
          message: "上传图片大小不能超过 2MB!",
          type: "warning",
          duration: 1800,
        });
      }
      return isLt2M;
    },
    //删除图片
    async imgRemove(file, fileList) {
      let data = {
        img_url: file.url,
        id: file.id
      }
      const [err, res] = await this.$http.request({
        url: "delPic",
        method: "POST",
        data
      });
      if (err) return;
      if (res.data.zhuangtai == "shanchuchenggong") {
        this.$message({
          showClose: true,
          message: "删除成功！",
          type: "success",
          duration: 1800,
        });
      }
    },
    //客服配置上传图片
    async servicePreview(response, file, fileList) {
      //上传图片到后端
      let  EPT_SERVICE = 1
      let fries = new FormData();
      fries.append("file", file.raw);
      fries.append("img_type", EPT_SERVICE);
      const [err, res] = await this.$http.request(
        {
          url: "/uploadPic",
          method: "POST",
          data: fries
        },
        // {
        //   baseURL: this.base,
        //   timeout: 5000,
        //   processData: false,
        //   contentType: false,
        // },
        // formdata
      );
      if (err) return;
      if (res.data.cuowutishi == "wenjianchaochu") {
        this.$message({
          showClose: true,
          message: "您已达到配置上限！",
          type: "error",
          duration: 1800,
        });
        return;
      }
      if (res.data.zhuangtai == "shangchuanchenggong") {
        this.$message({
          showClose: true,
          message: "添加成功！",
          type: "success",
          duration: 1800,
        });
        file.url = res.data.dizhi[0];
      }
    },
    //商务配置上传图片
    async businessPreview(response, file, fileList) {
      //传后后端
      let  EPT_BUSINESS = 2
      let fries = new FormData()
      fries.append("file", file.raw);
      fries.append("img_type", EPT_BUSINESS );
      const [err, res] = await this.$http.request(
        {
          url: "/uploadPic",
          method: "POST",
          data: fries
        },
        // {
        //   baseURL: this.base,
        //   timeout: 5000,
        //   processData: false,
        //   contentType: false,
        // },
        // formdata
      );
      if (err) return;
      if (res.data.cuowutishi == "wenjianchaochu") {
        this.$message({
          showClose: true,
          message: "您已达到配置上限！",
          type: "error",
          duration: 1800,
        });
        return;
      }
      if (res.data.zhuangtai == "shangchuanchenggong") {
        this.$message({
          showClose: true,
          message: "添加成功！",
          type: "success",
          duration: 1800,
        });
        file.url = res.data.dizhi[0];
      }
    },
    //编辑公告接口
    async saveAnnouncement() {
      const [err, res] = await this.$http.request({
        url: "/addNotice",
        method: "POST",
        data: {
          title: this.announcement.title,
          content: this.announcement.content,
        },
      });
      if (err) return;
      console.log(res.data.result)
      if (res.data.result === 1) {
        this.$message({
          showClose: true,
          message: "编辑成功！",
          type: "success",
          duration: 1800,
        });
        this.announcement.title = '',
        this.announcement.content = ''
      }
    },
    handleClick(tab, e) {
      switch (tab.index) {
        case "2":
          this.serviceImg();
          break;
      }
    },
    //获取并处理价格配置数据接口
    async priceLst() {
      const [err, res] = await this.$http.request({
        url: "/getPrice",
        method: "GET",
      });
      if (err) return;
      // console.log(res.data.data.above_price_list)
      //上级配置表
      this.listData = res.data.data.above_price_list
      //自己配置价格表
      this.dataList = res.data.data.self_price_list
    },
    //处理数组
    priceUnit(arr) {
      let arr2 = []
      this.showarr.forEach(item => {
        arr.forEach(item2 => {
          if (item.ziduan == item2.name) {
            item2.str = item.bieming
            item2.unit = item.danwei
          }
        })
      })
      arr.forEach((item, i) => {
        if (item.str) {
          let obj = {
            price: item.price,
            str: item.str,
            unit: item.unit,
            name: item.name
          }
          item.actualPrice ? obj.actualPrice = item.actualPrice : obj;
          arr2.push(obj)
        }
      })
      return arr2;
    },
    async confirmPrice(params1, params2) {
      let params3 = [];
      let params4 = [];
      for (let key in params1) {
        if (Number(params1[key]) > Number(params2[key]) * 2) {
          params3.push({
            name: key,
            price: Number(params2[key]) * 2,
          });
        }
        if (Number(params1[key]) < Number(params2[key])) {
          params4.push({
            name: key,
            price: Number(params2[key])
          })
        }
      }
      if (params4.length > 0) {
        this.actualPrice.forEach(item => {
          params4.forEach(item2 => {
            if (item2.name == item.name) {
              setTimeout(() => {
                this.$message({
                  showClose: true,
                  message: `${item.str}；最小不能小于${item.price}元！`,
                  type: "error",
                  duration: 1800,
                });
              }, 100);
            }
          })
        })
        return;
      }
      if (params3.length > 0) {
        this.actualPrice.forEach((item) => {
          params3.forEach(item2 => {
            if (item2.name == item.name) {
              setTimeout(() => {
                this.$message({
                  showClose: true,
                  message: `${item.str}；最高不能超过${item.price}元！`,
                  type: "error",
                  duration: 1800,
                });
              }, 100);
            }
          })
        })
        return;
      }
      const [err, res] = await this.$http.request({
        url: "updatePrice",
        method: "POST",
        data: { price_list: JSON.stringify(this.ceshi) },
      });
      if (err) return;
      if (res.data.zhuangtai == "chenggong") {
        this.$message({
          showClose: true,
          message: "修改成功！",
          type: "success",
          duration: 1800,
        });
        this.actualPrice.forEach((item) => {
          item.price = Number(item.actualPrice).toFixed(2);
          item.actualPrice = Number(item.actualPrice).toFixed(2);
        });
      } else if (res.data.code == "400") {
        console.log(res)
        this.$message({
          showClose: true,
          message: "修改失败，修改数据有误！",
          type: "error",
          duration: 1800,
        });
      } else {
        this.$message({
          showClose: true,
          message: "修改失败！",
          type: "error",
          duration: 1800,
        });
      }
    },
    //确定触发
    confirm: _debounce1(function (e) {
      let params1 = {};
      let params2 = {};
      const format = this.dataList.some((item) => {
        return Number(item.price).toFixed(2) === "NaN";
      });
      console.log(format)
      if (format) {
        this.$message({
          showClose: true,
          message: "修改失败，修改数据格式有误！",
          type: "error",
          duration: 1800,
        });
        return;
      }
      const blank = this.dataList.some((item) => {
        return item.price === "";
      });
      if (blank) {
        this.$message({
          showClose: true,
          message: "修改失败，价格不能为空！",
          type: "error",
          duration: 1800,
        });
        return;
      }
      this.dataList.forEach((item) => {

        params1[item.merchandise__id] = Number(item.price).toFixed(2);
      });
      // this.initialPrice.forEach((item) => {
      //   params2[item.name] = Number(item.price).toFixed(2);
      // });
      this.ceshi = params1
      this.confirmPrice(params1, params2);
    }),
  },
  components: {
    Editor
  },
};
</script>

<style scoped lang="stylus">
@import './Proxyconfiguration.styl';
</style>
